package com.mingqi.enetconnected.view.Dialog.tree;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.data.bean.config.GoodsInfo;
import com.mingqi.enetconnected.data.bean.config.GoodsType;
import com.mingqi.enetconnected.data.source.local.GoodsInfoLocalDataSource;
import com.mingqi.enetconnected.primary.mytask.event.ServiceGoodsEvent;
import com.mingqi.enetconnected.util.NormalKey;
import com.mingqi.enetconnected.view.Dialog.tree.indicator.IndicatorAdapter;
import com.mingqi.enetconnected.view.Dialog.tree.indicator.IndicatorView;

import org.greenrobot.eventbus.EventBus;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.mingqi.enetconnected.primary.mytask.event.ServiceGoodsEvent.EVENT_ADD_SERVICE;

/**
 * @author yaxi
 * @date 2018/9/17
 */
public class DynamicTreePopup extends PopupWindow implements View.OnClickListener, IndicatorView.OnItemSelectedListener {

    public static final String TAG = DynamicTreePopup.class.getSimpleName();


    private TextView mTreeTitle, mEnsure, mCancle;
    private IndicatorView mIndicatorView;
    private List<List<IDynamicTreeData>> mAll;
    private Context mContext;
    private RecyclerView mRecyclerView;
    private ContentAdapter mContentAdapter;

    private LinearLayout mPopupContainer;
    private LinearLayout mPopupTreeContainer;
    private LinearLayout mProgressContainer;

    private Disposable mDisposable;
    private final IndicatorAdapter mIndicatorAdapter;

    private String goodsTypeName;
    private GoodsInfo result;
    private final GoodsType treeData = new GoodsType() {
        @Override
        public String getShowLeft() {
            return mContext.getResources().getString(R.string.please_select);
        }
    };


    public DynamicTreePopup(Context context, boolean showCancel) {
        super(context);
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.popup_tree_content, null);
        setContentView(view);


        mTreeTitle = view.findViewById(R.id.tree_title);
        mEnsure = view.findViewById(R.id.tree_ensure);
        mCancle = view.findViewById(R.id.tree_cancle);
        mRecyclerView = view.findViewById(R.id.tree_recycler);
        mIndicatorView = view.findViewById(R.id.tree_indicator);
        mPopupContainer = view.findViewById(R.id.popup_container);
        mPopupTreeContainer = view.findViewById(R.id.popup_tree_container);
        mProgressContainer = view.findViewById(R.id.progress_container);

        mPopupContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mPopupTreeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: click");
            }
        });

        if (!showCancel) {
            mCancle.setVisibility(View.GONE);
        }

        mEnsure.setOnClickListener(this);
        mCancle.setOnClickListener(this);

        mAll = new ArrayList<>();

        mIndicatorAdapter = new IndicatorAdapter(new ArrayList<IDynamicTreeData>());
        mIndicatorView.setAdapter(mIndicatorAdapter);
        mIndicatorView.setOnItemSelectedListener(this);

        mContentAdapter = new ContentAdapter(mContext, new ArrayList<IDynamicTreeData>());
        LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mContentAdapter);

        mContentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //获取当前点击的对象
                List dataList = adapter.getData();
                IDynamicTreeData parentData = (IDynamicTreeData) dataList.get(position);
                //遍历当前列表，移除所有的数据选择状态
                for (Object datum : dataList) {
                    IDynamicTreeData item = (IDynamicTreeData) datum;
                    //如果本次点击的和之前选择的对象一致，则不做任何操作
                    if (item.getTreeSelected() && item.equals(parentData)) {
                        return;
                    }
                    item.setTreeSelected(false);
                }
                //将当前点击对象添加选择
                parentData.setTreeSelected(true);

                if (parentData.isLastLevel()) {
                    mContentAdapter.notifyDataSetChanged();
                    result = (GoodsInfo) parentData;
                    return;
                }
                result = null;
                GoodsType selectedGoodsType = (GoodsType) parentData;
                if (selectedGoodsType.getDataLevel() == 1){
                    goodsTypeName = selectedGoodsType.getTypeName();
                }
                getContentList(selectedGoodsType.getDataLevel() + 1,
                        selectedGoodsType.getId(), parentData);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tree_ensure:
                if (result != null){
                    ServiceGoodsEvent<GoodsInfo> event = new ServiceGoodsEvent<>(EVENT_ADD_SERVICE);
                    event.setT(result);
                    event.setExtraInfo(goodsTypeName);
                    EventBus.getDefault().post(event);
                }

                this.dismiss();
                break;
            case R.id.tree_cancle:
                this.dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemSelected(int level) {
        mContentAdapter.setNewData(mAll.get(level));
    }


    public DynamicTreePopup buildView() {
        setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        // 为PopupWindow菜单添加阴影时，其宽度和高度必须都设置为MATCH_PARENT
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setAnimationStyle(R.style.PopupWindowAnimStyle);
        setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), (Bitmap) null));
        getBackground().setAlpha(100);
        setFocusable(true);
        setOutsideTouchable(true);
        return this;
    }

    public DynamicTreePopup setTitle(String title) {
        mTreeTitle.setText(title);
        return this;
    }

    public void show(View parentView) {
        showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
        String rootId;
        try {
            rootId = GoodsInfoLocalDataSource.getInstance().getGoodsTypeId(NormalKey.GoodsTypeCode.CODE_SERVICE_CONTENT);
            getContentList(0, rootId, null);
        } catch (SQLException|IllegalStateException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取内容列表
     *
     * @param targetDataLevel 下一层的level
     * @param pId             选择的对象的id，通过下一层的pid或者goodsTypeId关联
     * @param parentData      选择的对象数据
     */
    private void getContentList(final int targetDataLevel, final String pId, final IDynamicTreeData parentData) {

        final List<IDynamicTreeData> goodsTypes = new ArrayList<>();

        Observable.create(new ObservableOnSubscribe<IDynamicTreeData>() {
            @Override
            public void subscribe(ObservableEmitter<IDynamicTreeData> emitter) throws Exception {
                if (targetDataLevel == 2) {
                    //查询商品信息
                    try {
                        List<GoodsInfo> goodsInfoList = GoodsInfoLocalDataSource.getInstance().getGoodsInfo(pId);
                        for (GoodsInfo goodsInfo : goodsInfoList) {
                            emitter.onNext(goodsInfo);
                        }
                        emitter.onComplete();
                    } catch (SQLException e) {
                        e.printStackTrace();
                        emitter.onError(e);
                    }
                } else if (targetDataLevel < 2) {
                    //查询类型信息
                    try {
                        List<GoodsType> goodsTypeList = GoodsInfoLocalDataSource.getInstance().getGoodsType(pId);
                        for (GoodsType goodsType : goodsTypeList) {
                            emitter.onNext(goodsType);
                        }
                        emitter.onComplete();
                    } catch (SQLException e) {
                        e.printStackTrace();
                        emitter.onError(e);
                    }
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<IDynamicTreeData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                        if (mProgressContainer.getVisibility() != View.VISIBLE) {
                            mProgressContainer.setVerticalGravity(View.VISIBLE);
                            mProgressContainer.requestFocus();
                        }
                    }

                    @Override
                    public void onNext(IDynamicTreeData goodsType) {
                        //设置等级
                        goodsType.setDataLevel(targetDataLevel);
                        goodsTypes.add(goodsType);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mProgressContainer.getVisibility() != View.GONE) {
                            mProgressContainer.setVerticalGravity(View.GONE);
                            mProgressContainer.clearFocus();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (mProgressContainer.getVisibility() != View.GONE) {
                            mProgressContainer.setVerticalGravity(View.GONE);
                            mProgressContainer.clearFocus();
                        }
                        //展示数据
                        treeData.setDataLevel(targetDataLevel);
                        if (targetDataLevel == 0) {
                            //添加树形结构标题数据
                            mIndicatorAdapter.addData(0,treeData);
                            mContentAdapter.setNewData(goodsTypes);
                            mAll.add(goodsTypes);
                            return;
                        }
                        //如果当前列表没有子列表，则直接增加一个子列表
                        //如果当前列表已有子列表，则清除子列表以及子列表对应的指示器和mAll的元素数据，
                        // 然后再增加对应的子列表

                        mContentAdapter.setNewData(goodsTypes);
                        if (targetDataLevel < mAll.size() ) {
                            int size = mAll.size();
                            for (int i = 0; i < size - targetDataLevel; i++) {
                                mAll.remove(targetDataLevel);
                            }
                            mAll.add(goodsTypes);
                            //除去请选择项外的其他多余项删除
                            int last = mIndicatorAdapter.getSize() - 1;
                            int start = targetDataLevel;
                            if (last - start > 0)
                            mIndicatorAdapter.removeRangeData(start,last-start);
                            mIndicatorAdapter.setData(targetDataLevel - 1, parentData);
                        } else {
                            mAll.add(goodsTypes);
                            mIndicatorAdapter.addData(mIndicatorAdapter.getCount() - 1, parentData);
                        }
                    }
                });

    }


    @Override
    public void dismiss() {
        super.dismiss();
        mIndicatorView.removeOnItemSelectedListener();
        if (mDisposable != null && !mDisposable.isDisposed()){
            mDisposable.dispose();
        }
    }
}
